package com.atzongmaotan.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.atzongmaotan.reggie.common.BaseContext;
import com.atzongmaotan.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * ClassName:    LoginCheckFilter
 * Package:  com.atzongmaotan.filter
 * Description:
 *
 * @Author: interface
 * @Create: 2024/6/12 - 上午6:51
 * @Version: v1.0
 */
@Slf4j
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    //路径匹配器,进行路径匹配
    public static final AntPathMatcher matcher = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        log.info("拦截到请求:{}",request.getRequestURI());
        String requestURI = request.getRequestURI();
        //判断是否不需要登陆
        String urls[] = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/sendMsg", //移动端发送短信
                "/user/login" //移动端登陆
        };
        boolean check = checkURL(urls, requestURI);
        if (check) {
            //不需要处理,直接访问
            log.info("本次请求{} 不需要被处理",request.getRequestURI());
            filterChain.doFilter(request, response);
            return;
        }
        //判断是否登陆,如果登陆则访问
        if (request.getSession().getAttribute("employee") != null){
            log.info("用户已登录,用户id为{}",request.getSession().getAttribute("employee"));
            Long empId = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentUserId(empId);
            filterChain.doFilter(request, response);
            return;
        }
        //移动端判断是否登陆,如果登陆则访问
        if (request.getSession().getAttribute("user") != null){
            log.info("用户已登录,用户id为{}",request.getSession().getAttribute("user"));
            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentUserId(userId);
            filterChain.doFilter(request, response);
            return;
        }

        //未登录则返回未登录结果,通过输出流返回JSON数据
        log.info("用户未登录");
        response.getWriter().print(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    public boolean checkURL(String[] urlList,String requestURI) {
        for (String url : urlList) {
            if (matcher.match(url, requestURI)) {
                return true;
            }
        }
        return false;
    }
}
